<template>
  <div class="real-name-auth">
    <h2>实名认证</h2>
    
    <el-steps :active="currentStep" finish-status="success" align-center>
      <el-step title="上传身份证" />
      <el-step title="人脸拍照" />
      <el-step title="验证结果" />
    </el-steps>
    
    <el-card class="auth-card">
      <!-- 第一步：上传身份证 -->
      <div v-if="currentStep === 1" class="step-content">
        <h3>上传身份证正面照片</h3>
        <div class="upload-section">
          <el-upload
            class="avatar-uploader"
            :action="uploadApi"
            :show-file-list="false"
            :on-success="handleIdCardUploadSuccess"
            :before-upload="beforeIdCardUpload"
            :on-error="handleUploadError"
            :headers="uploadHeaders"
          >
            <img v-if="idCardImage.url" :src="'http://syhx7nmey.hb-bkt.clouddn.com/'+idCardImage.url" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
          <p class="upload-tips">请确保照片清晰，身份证信息完整可见</p>
          
          <div class="button-group">
            <el-button type="primary" @click="nextStep" :disabled="!idCardImage.url">
              下一步
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 第二步：人脸拍照 -->
      <div v-if="currentStep === 2" class="step-content">
        <h3>请正对摄像头进行人脸拍照</h3>
        <div class="camera-section">
          <div class="camera-preview">
            <video ref="videoRef" autoplay playsinline class="video-element"></video>
            <canvas ref="canvasRef" class="canvas-element"></canvas>
          </div>
          
          <div class="capture-controls">
            <el-button @click="capturePhoto" type="primary" :loading="isCapturing">
              拍照
            </el-button>
            <el-button @click="retakePhoto" v-if="selfieImage.url">
              重拍
            </el-button>
          </div>
          
          <div v-if="selfieImage.url" class="capture-result">
            <h4>拍摄结果</h4>
            <img :src="selfieImage.url" alt="拍摄的照片" class="captured-image" />
          </div>
          
          <div class="button-group">
            <el-button @click="prevStep">上一步</el-button>
            <el-button 
              type="primary" 
              @click="verifyIdentity" 
              :disabled="!selfieImage.url" 
              :loading="isVerifying"
            >
              开始验证
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 第三步：验证结果 -->
      <div v-if="currentStep === 3" class="step-content">
        <h3>验证结果</h3>
        <div class="result-section">
          <div v-if="isVerifying" class="verifying">
            <el-icon class="loading-icon"><Loading /></el-icon>
            <p>正在验证中，请稍候...</p>
          </div>
          
          <div v-if="verificationResult" class="verification-result">
            <el-result
              :icon="verificationResult.success ? 'success' : 'error'"
              :title="verificationResult.success ? '实名认证成功' : '实名认证失败'"
              :sub-title="verificationResult.message"
            >
              <template #extra>
                <el-button v-if="!verificationResult.success" type="primary" @click="restartProcess">
                  重新认证
                </el-button>
                <el-button v-else type="primary" @click="goToUserCenter">
                  返回个人中心
                </el-button>
              </template>
            </el-result>
            
            <div class="id-card-info" v-if="verificationResult.idCardInfo">
              <h4>身份证信息</h4>
              <el-descriptions border>
                <el-descriptions-item label="姓名">{{ verificationResult.idCardInfo.name }}</el-descriptions-item>
                <el-descriptions-item label="身份证号">{{ verificationResult.idCardInfo.id_number }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ verificationResult.idCardInfo.gender }}</el-descriptions-item>
                <el-descriptions-item label="出生日期">{{ verificationResult.idCardInfo.birthday }}</el-descriptions-item>
              </el-descriptions>
            </div>
            
            <div class="similarity" v-if="verificationResult.similarity !== undefined">
              <h4>人脸相似度: {{ verificationResult.similarity }}%</h4>
              <el-progress 
                :percentage="verificationResult.similarity" 
                :status="verificationResult.similarity >= 80 ? 'success' : 'exception'"
                :text-inside="true"
                :stroke-width="20"
              />
              <p v-if="verificationResult.similarity >= 80" class="success-text">相似度达标，认证通过</p>
              <p v-else class="error-text">相似度不足，认证失败</p>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus, Loading } from '@element-plus/icons-vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();

// 步骤控制
const currentStep = ref(1);
const nextStep = () => currentStep.value++;
const prevStep = () => currentStep.value--;

// 上传配置 - 使用您提供的七牛云上传接口
const uploadApi = ref('http://127.0.0.1:8000/goods/upload/'); // 修改为您的上传接口路径
const uploadHeaders = ref({
  Authorization: `Bearer ${localStorage.getItem('token')}`
});

// 第一步：身份证上传
const idCardImage = ref({
  url: '',
  key: ''
});

const beforeIdCardUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return false;
  }

  return true;
};

const handleIdCardUploadSuccess = (response) => {
  if (response.code === 10000) {
    idCardImage.value = {
      url: response.data.url, // 使用七牛云返回的URL
      key: response.data.key  // 保存七牛云的key
    };
    ElMessage.success('身份证上传成功');
  } else {
    ElMessage.error(response.message || '身份证上传失败');
  }
};

// 第二步：人脸拍照
const videoRef = ref(null);
const canvasRef = ref(null);
const isCameraActive = ref(false);
const selfieImage = ref({
  url: '',
  key: ''
});
const isCapturing = ref(false);
const stream = ref(null);

// 启动摄像头
const startCamera = async () => {
  try {
    stopCamera();
    
    stream.value = await navigator.mediaDevices.getUserMedia({
      video: {
        width: { ideal: 1280 },
        height: { ideal: 720 },
        facingMode: 'user'
      },
      audio: false
    });
    
    if (videoRef.value) {
      videoRef.value.srcObject = stream.value;
    }
    
    isCameraActive.value = true;
  } catch (error) {
    console.error('摄像头访问失败:', error);
    ElMessage.error(`无法访问摄像头: ${error.message}`);
  }
};

// 拍照
const capturePhoto = () => {
  if (!isCameraActive.value || !videoRef.value || !canvasRef.value) return;
  
  isCapturing.value = true;
  
  const video = videoRef.value;
  const canvas = canvasRef.value;
  
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  
  const ctx = canvas.getContext('2d');
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  
  selfieImage.value.url = canvas.toDataURL('image/jpeg', 0.8);
  isCapturing.value = false;
};

// 重拍
const retakePhoto = () => {
  selfieImage.value = {
    url: '',
    key: ''
  };
};

// 停止摄像头
const stopCamera = () => {
  if (stream.value) {
    stream.value.getTracks().forEach(track => track.stop());
    stream.value = null;
  }
  
  if (videoRef.value) {
    videoRef.value.srcObject = null;
  }
  
  isCameraActive.value = false;
};

// 第三步：验证身份
const isVerifying = ref(false);
const verificationResult = ref(null);

const verifyIdentity = async () => {
  if (!idCardImage.value.key || !selfieImage.value.url) return;
  
  isVerifying.value = true;
  verificationResult.value = null;
  
  try {
    // 1. 先上传自拍照片到七牛云
    const blob = await fetch(selfieImage.value.url).then(r => r.blob());
    const file = new File([blob], 'selfie.jpg', { type: 'image/jpeg' });
    
    const formData = new FormData();
    formData.append('file', file);
    
    const uploadResponse = await axios.post(uploadApi.value, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        ...uploadHeaders.value
      }
    });
    
    if (uploadResponse.data.code !== 10000) {
      throw new Error(uploadResponse.data.message || '自拍照片上传失败');
    }
    
    selfieImage.value.key = uploadResponse.data.data.key;
    
    // 2. 调用验证接口
    const verifyResponse = await axios.post('http://127.0.0.1:8000/ai/renlian/', {
      image_a:'http://syhx7nmey.hb-bkt.clouddn.com/' +idCardImage.value.key,  // 修改参数名为image_a
      image_b:"http://syhx7nmey.hb-bkt.clouddn.com/"+ selfieImage.value.key   // 修改参数名为image_b
      // user_id: localStorage.getItem('userId')
    });
    
    // 处理新的响应格式
    const score = verifyResponse.data.detail?.result?.score;
    const isSuccess = score >= 80; // 大于等于80分则认证通过
    
    verificationResult.value = {
      success: isSuccess,
      message: isSuccess ? '人脸匹配成功' : '人脸匹配失败',
      similarity: score,
      details: verifyResponse.data
    };
    
    if (isSuccess) {
      ElMessage.success('实名认证成功');
      
      // 3. 认证通过后调用百度OCR识别身份证信息
      try {
        const ocrResponse = await axios.post('http://127.0.0.1:8000/ai/id_card/', {
          url: 'http://syhx7nmey.hb-bkt.clouddn.com/' + idCardImage.value.key
        });
        
        if (ocrResponse.data.code === 10000) {
          const idCardInfo = ocrResponse.data.data;
          
          // 4. 更新用户实名信息
          const updateResponse = await axios.post('http://127.0.0.1:8000/login/userauth/', {
            user_id: localStorage.getItem('user_id'),
            name: idCardInfo.name,
            id_number: idCardInfo.id_number,
            gender: idCardInfo.gender,
            ethnicity: idCardInfo.ethnic,
            birth_date: idCardInfo.birthday,
            address: idCardInfo.address
          }, {
            headers: {
              'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
          });
          
          if (updateResponse.data.code === 200) {
            ElMessage.success('用户实名信息更新成功');
            // 将身份证信息保存到验证结果中用于显示
            verificationResult.value.idCardInfo = idCardInfo;
          } else {
            ElMessage.warning('实名认证成功，但信息更新失败: ' + updateResponse.data.message);
          }
        } else {
          ElMessage.warning('实名认证成功，但身份证识别失败: ' + ocrResponse.data.message);
        }
      } catch (error) {
        console.error('身份证识别或信息更新失败:', error);
        ElMessage.warning('实名认证成功，但身份证信息处理异常');
      }
    } else {
      ElMessage.error('人脸匹配失败，请重试');
    }
    
    nextStep();
  } catch (error) {
    console.error('实名认证失败:', error);
    verificationResult.value = {
      success: false,
      message: error.response?.data?.message || '实名认证服务异常，请稍后重试',
      details: error.response?.data
    };
    ElMessage.error('实名认证失败，请重试');
  } finally {
    isVerifying.value = false;
  }
};

// 重新开始流程
const restartProcess = () => {
  currentStep.value = 1;
  verificationResult.value = null;
  retakePhoto();
};

// 返回个人中心
const goToUserCenter = () => {
  router.push('/user/center');
};


const card_id = () => {
  axios.post('http://127.0.0.1:8000/ai/id_card/', {
    url:'http://syhx7nmey.hb-bkt.clouddn.com/' +idCardImage.value.key,  // 替换为你的身份证图片的URL

  })
  .then(response => {
    console.log(response.data);
    ElMessage.success('身份证识别成功');
    nextStep();
  })
  .catch(error => {
    console.error(error);
    ElMessage.error('身份证识别失败，请重试');
  });
};

const face_id = () => {
  axios.post('http://127.0.0.1:8000/ai/face/', {
    face: fileData.value
  })
  .then(response => {
    console.log(response.data);
    ElMessage.success('人脸识别成功');
    nextStep();
    
  })
};

// 处理上传错误
const handleUploadError = (error) => {
  console.error('上传错误:', error);
  ElMessage.error('上传失败，请重试');
};

// 生命周期钩子
onMounted(() => {
  if (currentStep.value === 2) {
    startCamera();
  }
});

onUnmounted(() => {
  stopCamera();
});

// 监听步骤变化
watch(currentStep, (newVal) => {
  if (newVal === 2) {
    nextTick(() => {
      startCamera();
    });
  } else {
    stopCamera();
  }
});
</script>

<style scoped>
.real-name-auth {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.auth-card {
  margin-top: 20px;
  padding: 20px;
}

.step-content {
  min-height: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-section, .camera-section, .result-section {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 250px;
  margin: 20px 0;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
}

.upload-tips {
  text-align: center;
  color: #999;
  font-size: 14px;
  margin-bottom: 20px;
}

.camera-preview {
  position: relative;
  width: 100%;
  max-width: 500px;
  margin: 20px auto;
  border: 2px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
  background-color: #000;
}

.video-element {
  display: block;
  width: 100%;
  height: auto;
}

.canvas-element {
  display: none;
}

.capture-controls {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin: 20px 0;
}

.capture-result {
  margin: 20px 0;
  text-align: center;
}

.captured-image {
  max-width: 100%;
  max-height: 300px;
  border-radius: 8px;
  border: 1px solid #ddd;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
}

.verifying {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.loading-icon {
  font-size: 50px;
  color: #409eff;
  margin-bottom: 20px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.verification-result {
  width: 100%;
}

.id-card-info {
  margin: 20px 0;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.similarity {
  margin: 20px 0;
  text-align: center;
}

.success-text {
  color: #67c23a;
  font-weight: bold;
}

.error-text {
  color: #f56c6c;
  font-weight: bold;
}

.el-progress {
  margin: 20px auto;
  max-width: 300px;
}
</style>